<template>
  <div>
    <!-- 搜索 -->
    <form action="/">
      <van-search
        v-model="value"
        show-action
        background="#f6f5f6"
        placeholder="请输入搜索关键词"
        @input="inputFn"
        @cancel="onCancel"
      />
    </form>
      <!-- 搜索建议列表 -->
    <div
      class="sugg-list"
      v-for="(item, index) in suggestionList"
      :key="index"
    >
      <div class="sugg-item"  v-html="lightFn(item, value)" @click="clickFn(item)"></div>
    </div>
  </div>
</template>

<script>
import { Toast } from 'vant'
import { houseCommunityAPI } from '@/api'
export default {
  data () {
    return {
      value: '', // 搜索关键字
      timer: null,
      suggestionList: []
    }
  },
  methods: {
    // 搜索
    inputFn () {
      // 清除定时器
      clearTimeout(this.timer)
      // 防抖
      this.timer = setTimeout(async () => {
        if (this.value.length === 0) return
        const res = await houseCommunityAPI({
          name: this.value,
          id: localStorage.getItem('newCityCode')
        })
        console.log(res)
        this.suggestionList = res.data.body.map(item => item.communityName)
      }, 500)
    },
    // 使用replace用于替换字符串，实现搜索结果高亮
    lightFn (old, target) {
      // /ig/语法糖正确写法，不支持传参，所以需要new RegExp实现正则
      const regExp = new RegExp(target, 'ig')
      return old.replace(regExp, (match) => {
        return `<span style="color: red">${match}</span>`
      })
    },
    clickFn (item) {
      console.log(item)
      // 将搜索值传出去
      this.$router.push({
        // name: 'torent',
        // params: item
        path: `/torent/?name=${item}`
      })
    },
    onCancel () {
      Toast('取消')
      this.$router.back()
    }
  }
}
</script>

<style lang="less" scoped>
.van-search {
  padding: 5px 1px 5px 9px;
}
.van-field__control{
  background-color: #fff;
}
/*搜索建议列表样式 */
.sugg-list {
  .sugg-item {
    padding: 0 15px;
    border-bottom: 1px solid #f8f8f8;
    font-size: 14px;
    line-height: 45px;
    // 实现省略号的三行代码
    white-space: nowrap;
    text-align: left;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style>
